package ch.qos.logback.web.spi;

import ch.qos.logback.classic.BasicConfigurator;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.Configurator;
import ch.qos.logback.classic.util.ContextInitializer;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.spi.ContextAwareBase;
import ch.qos.logback.core.status.ErrorStatus;
import ch.qos.logback.core.status.StatusManager;
import ch.qos.logback.core.util.Loader;

import java.net.URL;

/**
 * Created by Administrator on 2016/1/21.
 */
public class WebConfigurator extends ContextAwareBase implements Configurator {

    @Override
    public void configure(LoggerContext loggerContext) {
        ContextInitializer contextInitializer = new MyContextInitializer(loggerContext);
        URL url = contextInitializer.findURLOfDefaultConfigurationFile(true);
        boolean initialized = false;
        if (url != null) {
            try {
                contextInitializer.configureByResource(url);
                initialized = true;
            } catch (JoranException e) {
                StatusManager sm = loggerContext.getStatusManager();
                sm.add(new ErrorStatus("failed when trying to configure by resource, url=" + url, loggerContext, e));
            }
        }
        if (!initialized) {
            BasicConfigurator.configure(loggerContext);
        }
    }

    private class MyContextInitializer extends ContextInitializer {

        public MyContextInitializer(LoggerContext loggerContext) {
            super(loggerContext);
        }

        @Override
        public URL findURLOfDefaultConfigurationFile(boolean updateStatus) {
            ClassLoader myClassLoader = Thread.currentThread().getContextClassLoader();
            URL url = Loader.getResource(GROOVY_AUTOCONFIG_FILE, myClassLoader);
            if (url != null) {
                return url;
            }

            url = Loader.getResource(TEST_AUTOCONFIG_FILE, myClassLoader);
            if (url != null) {
                return url;
            }

            return Loader.getResource(AUTOCONFIG_FILE, myClassLoader);
        }
    }
}
